import React from 'react';
import {StyleSheet, View} from 'react-native';
import SharePlatform from "../../../share/SharePlatform";
import UShare from "../../../share/share";
import Toast from 'react-native-easy-toast';

import auth from '../../../common/auth';
import api from "../../../common/api";

import Header from '../../../components/header';
import Avatar from './avatar';
import Link from './link';
import Loading from '../../../components/loading';
import config from "../../../common/config";

export default class extends React.Component {
    state = {
        userInfo: {},
        isLoading: false
    };
    //上传头像
    uploadAvatar = avatar => {
        const {isLoading, userInfo} = this.state;
        if (isLoading) {
            return;
        }
        this.setState({
            isLoading: true
        });
        let formData = new FormData();
        let file = {uri: avatar, type: 'multipart/form-data', name: 'a.jpg'};

        formData.append('imgData', file);
        formData.append('user_id', userInfo.id);
        formData.append('userId', userInfo.id);

        fetch(`${config.baseUrl}api/member/uploadUserImg`, {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data',
            },
            body: formData
        })
            .then(
                (response) => response.text()
            )
            .then((res) => {
                console.log('结果是', res);
                if (res.errno === 0) {
                    resolve(res.result);
                    this.showToast('上传成功');
                } else {
                    this.showToast('上传失败');
                }
            })
            .catch((e) => {
                console.error(e);
                this.showToast('上传失败');
            })
            .finally(() => {
                this.setState({
                    isLoading: false
                });
            });
    };
    //退出
    loginOut = () => {
        auth.removeUserInfo()
            .then(() => {
                auth.goBack();
            })
            .catch(e => {
                console.error(e);
            })
    };

    //绑定微信
    bindWechat = () => {
        UShare.authLogin(SharePlatform.WECHAT, (result) => {
            const {code, userName, userAvatar, userId, userGender} = result;
            if (code === 0) {
                this.setState({
                    isLoading: true
                });
                api({
                    url: 'api/member/bindWxInfo',
                    data: {nickname: userName, openid: userId, unionid: userId, avatar: userAvatar, userGender}
                })
                    .then(() => {
                        this.showToast('绑定成功');
                    })
                    .catch(e => {
                        this.showToast(e.msg);
                    })
                    .finally(() => {
                        this.setState({
                            isLoading: false
                        });
                    });
            } else {
                this.showToast('授权失败');
            }
        });
    };

    //toast弹出
    showToast = (text, time = 1000) => {
        this.refs.toast.show(text, time);
    };

    componentDidMount() {
        auth.getUserInfo()
            .then(userInfo => {
                this.setState({
                    userInfo: userInfo
                });
            })
            .catch(() => {
                auth.goBack();
            });
    }

    render() {
        const {isLoading} = this.state;
        const {navigation} = this.props;
        return (
            <View style={styles.container}>
                <Header title="设置"/>
                <Avatar uploadAvatar={this.uploadAvatar}/>
                <Link navigation={navigation}
                      loginOut={this.loginOut}
                      bindWechat={this.bindWechat}
                      showToast={this.showToast}/>
                <Loading isLoading={isLoading} loadingText="正在上传..."/>
                <Toast ref="toast" position="center"/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#f0f0f0',
        flex: 1
    }
});
